﻿using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using DotNetCommon.Extensions;
using System.Diagnostics;

namespace WebUserTest
{
    public class MyBackGroupService : IHostedService
    {
        public Task StartAsync(CancellationToken cancellationToken)
        {
            return Task.Factory.StartNew(async () =>
            {
                //监视用户创建
                DotNetCommon.User.UserCreated += (user) =>
                {
                    Console.WriteLine("New User");
                };
                //等web程序启动
                await Task.Delay(1000);
                //模拟一段异步代码
                for (var i = 0; i < 10; i++)
                {
                    Console.WriteLine();
                    Console.WriteLine($"第 {i + 1} 次异步");
                    var requestId = "request_" + (i + 1);
                    await DoWork(requestId);
                }

            }, TaskCreationOptions.LongRunning);
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine("Stop");
            return Task.CompletedTask;
        }

        /// <summary>
        /// 必须打上 async 标记，否则 多次执行DoWork会使用相同的User实例
        /// </summary>
        /// <param name="requestId"></param>
        /// <returns></returns>
        public async Task DoWork(string requestId)
        {
            var user = DotNetCommon.User.Current;
            var ContainsProperty = user.ContainsProperty("key");
            Debug.Assert(ContainsProperty == false);
            user.SetProperty("key", requestId);
            var GetProperty = user.GetProperty<string>("key");
            Debug.Assert(GetProperty == requestId);
        }
    }
}
